const app = getApp()
const WXNEWAPI = require("../../../api/newApi")
const WXAPI = require("../../../api/api")
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    assetId: '',
    info: {},
    shopLs: [], //商家列表
    imgHttp: app.globalData.imgHttp,
    pageSize: 10,
    pageNum: 1,
    cardTotal: 0,
    lnt: '', //用户经度
    lat: '', //用户纬度
    lodingtype: 1, //加载状态（0：加载中  1：加载完成没有更多)
    isToken: false, //是否授权
    code: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // wx.clearStorageSync()
    this.setData({
      statusHeight: app.gettop.height,
      status: app.gettop.status,
      navHeight: app.gettop.navHeight,
      mobbleBottom: app.mobile.mobbleBottom,
    })
    var wxUrl = decodeURIComponent(options.q)
    if (wxUrl == 'undefined') {
      console.log('是undefined的情况')
      this.data.assetId = decodeURIComponent(options.assetId)
    } else {
      console.log('不是undefined的情况')
      var num = wxUrl.indexOf("=")
      var id = wxUrl.substring(num + 1, wxUrl.length);
      this.data.assetId = id
    }
    console.log('wxUrl', wxUrl)
    // this.data.assetId = '1481582032445296641'
    qqmapsdk = new QQMapWX({
      key: '5TMBZ-NASKV-ER5PO-ULIJO-CE6MZ-O4BAQ'
    });
    var optionss = JSON.stringify(options)
    // this.setData({
    //   wxUrl: wxUrl,
    //   optionss: optionss,
    //   assetId: this.data.assetId
    // })
    console.log('optionss是',optionss)
    console.log('this.data.assetId', this.data.assetId)
    console.log(app.globalData)
    this.data.lnt = app.globalData.lnt
    this.data.lat = app.globalData.lat
    // this.getCode()
    this.isGetSetting()
    this.getInfo()

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // wx.clearStorageSync()
    this.getCode()

    // 
    // var token = wx.getStorageSync('token')
  },
  loginSuccess() {
    console.log('成功')
    // this.getInfo()
    // this.getshopLs()
    // wx.navigateTo({
    //   url: './card/card',
    // })
  },
  receiveClick() {
    // this.login_dialog = this.selectComponent("#login_dialog");
    // var token = wx.getStorageSync('token')
    // if (token == '') {
    //   this.login_dialog.loginShow()
    // } else {
    //   this.login_dialog.loginHide()
    //   wx.navigateTo({
    //     url: './card/card',
    //   })
    // }
    wx.navigateTo({
      url: './card/card?assetId=' + this.data.assetId,
    })
  },
  getInfo() { //获取卡信息
    var data = {
      assetId: this.data.assetId
    }
    WXNEWAPI.wealDrawInfo(data, (res) => {
      if (res.code == 200) {
        this.setData({
          info: res.result
        })
      }
    })
  },
  getshopLs() { //获取列表
    wx.showLoading({
      title: '加载中',
    })
    var data = {
      pageNum: this.data.pageNum,
      pageSize: this.data.pageSize,
      assetId: this.data.assetId,
      lnt: this.data.lnt, //用户经度
      lat: this.data.lat, //用户纬度
    }
    WXNEWAPI.assetCardWealShopInfo(data, (res) => {
      const data = res.result
      if (res.code == 200) {
        // this.data.cardtotal = res.result.total
        if (res.result.total == -1) {
          this.data.cardTotal = 0
        } else {
          this.data.cardTotal = res.result.total
        }
        this.setData({
          cardTotal: this.data.cardTotal
        })
        console.log("判断", this.data.pageNum, Math.ceil(this.data.cardTotal / this.data.pageSize), this.data.cardTotal)
        if (this.data.pageNum >= Math.ceil(this.data.cardTotal / this.data.pageSize)) {
          this.setData({
            lodingtype: 1
          })
        } else {
          this.setData({
            lodingtype: 0
          })
        }
        if (this.data.pageNum > 1) {
          this.data.shopLs = this.data.shopLs.concat(res.result.records); //将数据拼接在一起
          this.setData({
            shopLs: this.data.shopLs
          })
        } else {
          this.data.shopLs = res.result.records
          this.setData({
            shopLs: this.data.shopLs
          })
        }
        wx.hideLoading({})
      }
    })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log("触底了", this.data.pageNum, Math.ceil(this.data.cardTotal / this.data.pageSize), this.data.cardTotal)
    if (this.data.pageNum >= Math.ceil(this.data.cardTotal / this.data.pageSize)) {
      console.log('没有分页')
      this.setData({
        lodingtype: 1
      })
    } else {
      this.setData({
        lodingtype: 0
      })
      this.data.pageNum++; //每触底一次 page + 1;
      this.getshopLs();
    }
  },
  //跳转店铺
  handleShop(e) {
    var id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/userPageB/pages/userStore/storesDetails/storesDetails?shopId=' + id,
    })
  },
  //匿名支付获取token
  getToken() {
    var code = this.data.code
    console.log('code2222', code)
    var data = {
      code: code,
      appid: app.globalData.appid,
    }
    WXAPI.silentAuthorization(data, (res) => {
      const data = res.result
      console.log("开始获取token", res)
      if (res.code === 200) {
        wx.setStorageSync('token', data.token)
        // this.onLoad(this.data._options)
        // this.setData({
        //   anonymity: data.anonymity,
        // })
      }
    })
  },
  getCode() {
    // 登录 
    let that = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          that.setData({
            code: res.code
          })
          console.log('res.code', res.code)
          var token = wx.getStorageSync('token')
          console.log('token++++++', token)
          if (token == '') {
            setTimeout(() => {
              that.getToken()
            }, 1000)
          }
        } else {
          console.log('获取code失败', res.errMsg)
        }
      }
    })
  },
  //授权手机号码
  getPhoneNumber: function (e) {
    let that = this;
    that.getCode()
    setTimeout(() => {
      if (e.detail.errMsg == 'getPhoneNumber:ok') {
        console.log("点击事件", that.data.code)
        let data = {
          appid: app.globalData.appid,
          code: that.data.code,
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
          source: app.globalData.source,//用户来源
        }
        WXAPI.newgetPhone('no', data, (res) => {
          let data = res.result
          if (res.result) {
            if (data.token) {
              wx.clearStorageSync()
              wx.setStorageSync('token', data.token)
            }
            wx.setStorageSync('phone', data.phone)
            this.setData({
              isToken: true
            })
            this.receiveClick()

            // if (data.token) {
            //   wx.setStorageSync('token', data.token)
            //   wx.setStorageSync('phone', data.phone)
            //   this.setData({
            //     isToken: true
            //   })
            //   this.receiveClick()
            // } else {
            //   var authorizaData = {}
            //   app.globalData.phone = data.phone;
            //   authorizaData.sessionKey = data.sessionKey;
            //   authorizaData.encryption = data.encryption;
            //   authorizaData.phone = data.phone;
            //   this.setData({
            //     authorizaData: authorizaData
            //   })
            //   // this.dialog.showUser()
            // }
          }
        })
      } else if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
        //ios拒绝授权  
        that.setData({
          isphoneBox: false
        })
        that.triggerEvent("notokenFuntion");
      } else if (e.detail.errMsg == 'getPhoneNumber:fail:user deny') {
        //安卓拒绝授权    
        that.setData({
          isphoneBox: false
        })
        that.triggerEvent("notokenFuntion");
      }
    }, 500)

  },
  //二次唤起授权位置信息
  authorizedAddress(e) {
    this.isGetSetting()
  },
  onArrshow(e) {
    this.setData({
      permissions_Addr: e.detail
    })
  },
  //判断是否开启位置
  judgeArrd() {
    var that = this
    wx.getSetting({
      success: (res) => {
        var statu = res.authSetting;
        if (!statu['scope.userLocation']) { //未授权
          console.log('未授权位置信息')
          that.setData({
            permissions_Addr: true,
          })
        }
      }
    })
  },
  isGetSetting() { //获取位置授权
    wx.showLoading({
      title: '加载中',
      mask: true,
    })
    var that = this;
    // 判断用户是否授权
    wx.getSetting({
      success: (res) => {
        var statu = res.authSetting;
        if (!statu['scope.userLocation']) { //没授权
          //1、获取当前位置坐标
          wx.getLocation({
            type: 'gcj02',
            success: function (res) {
              console.log("经纬度", res)
              app.globalData.lat = res.latitude //维度
              app.globalData.lnt = res.longitude //经度
              qqmapsdk.reverseGeocoder({
                location: {
                  latitude: res.latitude,
                  longitude: res.longitude,
                },
                success: function (res) {
                  console.log('地址', res)
                }
              })
              that.setData({
                lat: res.latitude, //维度
                lnt: res.longitude, //经度
                unauthorized: true,
              })
              that.getshopLs()
            },
            fail: function (res) {
              that.getshopLs()
              that.setData({
                unauthorized: false,
              })
            },
          })
        } else {
          wx.getLocation({
            type: 'gcj02',
            success: function (res) {
              console.log("经纬度", res)
              app.globalData.lat = res.latitude //维度
              app.globalData.lnt = res.longitude //经度
              that.setData({
                lat: res.latitude, //维度
                lnt: res.longitude, //经度
                unauthorized: true,
              })
              qqmapsdk.reverseGeocoder({
                location: {
                  latitude: res.latitude,
                  longitude: res.longitude
                },
                success: function (res) {
                  console.log('地址', res)
                }
              })
              that.getshopLs()
            },
            fail: function (res) {
              that.getshopLs()
              that.setData({
                unauthorized: false,
              })
            },
          })
        }
      },
      fail: function (res) {
        wx.hideLoading();
      },
    })
  },
  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})